/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.DanhMucDAO;
import dao.DanhMucNhaSanXuatDAO;
import dao.HinhAnhDAO;
import dao.LoaiDauGiaDAO;
import dao.NhaSanXuatDAO;
import dao.SanphamDAO;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import javax.faces.application.Application;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Danhmuc;
import model.DanhmucNhasanxuat;
import model.Hinhanh;
import model.Nhasanxuat;
import model.Sanpham;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author HoangLiem
 */
@WebServlet(name = "xuLyThemSanPham", urlPatterns = {"/xuLyThemSanPham"})
public class xuLyThemSanPham extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            List<String> dsTenHinhAnh = new ArrayList<String>();
            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (!isMultiPart) {//to do
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();
                String fileName = null;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        params.put(item.getFieldName(), item.getString("UTF-8"));
                    } else {
                        try {
                            String itemName = item.getName();
                            fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                            String RealPath = getServletContext().getRealPath("/") + "images\\productImages\\" + fileName;
                            File saveFile = new File(RealPath);
                            item.write(saveFile);
                            String tenHinhAnh =  fileName;//"images/productImages/"+
                            boolean tonTaiHinh = false;
                            if (dsTenHinhAnh.size() <= 0) {
                                dsTenHinhAnh.add(tenHinhAnh);
                            } else {
                                for (int iTenHinh = 0; iTenHinh < dsTenHinhAnh.size(); iTenHinh++) {
                                    if (dsTenHinhAnh.get(iTenHinh).equals(tenHinhAnh)) {
                                        tonTaiHinh = true;
                                        break;
                                    }
                                }
                                if (tonTaiHinh == false) {
                                    dsTenHinhAnh.add(tenHinhAnh);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }//end while
             
                Sanpham sanPham = new Sanpham();
                sanPham.setMaSanPham(SanphamDAO.generateMaSp());
                if (params.get("tenSanPham") != null) {
                    sanPham.setTenSanPham(SanphamDAO.chuanHoaTenSp((String) params.get("tenSanPham")));
                }
                if (params.get("moTa") != null) {
                    sanPham.setMoTa((String) params.get("moTa"));
                }
                if (params.get("giaKhoiDiem") != null) {
                    sanPham.setGiaKhoiDiem(Float.parseFloat((String) params.get("giaKhoiDiem")));
                }
                if (params.get("giaBanLien") != null) {
                    sanPham.setGiaBanLien(Float.parseFloat((String) params.get("giaBanLien")));
                }
                //Lay ngay bat dau
                int ngay = 1, thang = 1, nam = 2011,gio=0,phut=0;
                if (params.get("thangNBD") != null) {
                    thang = Integer.parseInt((String)params.get("thangNBD"));
                }
                if (params.get("ngayNBD") != null) {
                    ngay = Integer.parseInt((String)params.get("ngayNBD"));
                }
                if (params.get("namNBD") != null) {
                    nam = Integer.parseInt((String)params.get("namNBD"));
                }
                if (params.get("gioNBD") != null) {
                    gio = Integer.parseInt((String)params.get("gioNBD"));
                }
                if (params.get("phutNBD") != null) {
                    phut = Integer.parseInt((String)params.get("phutNBD"));
                }
                
                Calendar cal = Calendar.getInstance();
                cal.set(nam, thang-1, ngay,gio,phut);
                sanPham.setThoiDiemBatDau(cal.getTime());
                
                if (params.get("thangNKT") != null) {
                    thang = Integer.parseInt((String)params.get("thangNKT"));
                }
                if (params.get("ngayNKT") != null) {
                    ngay = Integer.parseInt((String)params.get("ngayNKT"));
                }
                if (params.get("namNKT") != null) {
                    nam = Integer.parseInt((String)params.get("namNKT"));
                }
                if (params.get("gioNKT") != null) {
                    gio = Integer.parseInt((String)params.get("gioNKT"));
                }
                if (params.get("phutNKT") != null) {
                    phut = Integer.parseInt((String)params.get("phutNKT"));
                }

                cal.set(nam, thang-1, ngay,gio,phut);             
                sanPham.setThoiDiemKetThuc(cal.getTime());
                sanPham.setTinhTrang(1);
                sanPham.setTrangThai(false);
                
                int maLoaiDauGia = 1;
                if (params.get("maLoaiDauGia") != null) {
                    maLoaiDauGia = Integer.parseInt((String)params.get("maLoaiDauGia"));
                }
                sanPham.setLoaidaugia(LoaiDauGiaDAO.getABidType(maLoaiDauGia));
                
                String maDanhMuc = "";
                if (params.get("maDanhMuc") != null) {
                    maDanhMuc = (String)params.get("maDanhMuc");
                }
                String maNhaSanXuat="";
                if (params.get("maNhaSanXuat") != null) {
                    maNhaSanXuat = (String)params.get("maNhaSanXuat");
                }
                Danhmuc danhMuc = DanhMucDAO.getCategoryById(maDanhMuc);
                Nhasanxuat nhaSanXuat = NhaSanXuatDAO.getManufacturerById(maNhaSanXuat);
                DanhmucNhasanxuat dmNsx = DanhMucNhaSanXuatDAO.getACategory_Manufacturer(danhMuc, nhaSanXuat);
                if(dmNsx==null){
                    dmNsx = new DanhmucNhasanxuat();
                    String maDmNsx = DanhMucNhaSanXuatDAO.generate(danhMuc, nhaSanXuat);
                    dmNsx.setMaDanhMucNhaSanXuat(maDmNsx);
                    dmNsx.setDanhmuc(danhMuc);
                    dmNsx.setNhasanxuat(nhaSanXuat);
                    DanhMucNhaSanXuatDAO.insert(dmNsx);
                    sanPham.setDanhmucNhasanxuat(dmNsx);
                }else{
                    sanPham.setDanhmucNhasanxuat(dmNsx);
                }
                boolean result = false;
                result = SanphamDAO.insertOrUpdate(sanPham);
                if (result == true) {
                    if (dsTenHinhAnh.size() > 0) {
                        for (int hinh = 0; hinh < dsTenHinhAnh.size(); hinh++) {
                            Hinhanh ha = new Hinhanh();
                            ha.setTenHinhAnh(dsTenHinhAnh.get(hinh));
                            ha.setSanpham(sanPham);
                            boolean result1 = HinhAnhDAO.insert(ha);
                        }
                    }
                    response.sendRedirect("themSanPham?themThanhCong=1");     
                } else {
                    response.sendRedirect("themSanPham?themThanhCong=0");
                }
            }
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
